import datetime

from django.db import models
from django.utils import timezone


def format_datetime(date):
    if not date:
        return ''
    return date.strftime('%Y-%m-%d %H:%M:%S')


class TaskStatus(models.IntegerChoices):
    PADDING = 0, '有效'
    DONE = 1, '失效'


# Create your models here.
class Task(models.Model):
    title = models.CharField('标题', max_length=200)
    created_time = models.DateTimeField('创建日期')
    doing_time = models.DateTimeField('执行时间', null=True)
    status = models.IntegerField('状态', choices=TaskStatus.choices, default=TaskStatus.PADDING)
    deadline = models.IntegerField('剩余时间(s)', default=3600)
    loop = models.BooleanField('周期性', default=False)

    """
    任务配置(Json):
    {
        "url": "http://user.esoaru.net/xxx",
        "method": "post",
        "body": {
             "a": 1,
             "b": 2
        }
    }
    """

    running = models.TextField("执行任务配置", default='', blank=True, null=True)
    failed = models.TextField("执行错误配置", default='', blank=True, null=True)

    def serializer(self):
        return {
            'id': self.pk,
            'title': self.title,
            'status': self.status,
            'loop': self.loop,
            'created_time': format_datetime(self.created_time)
        }

    class Meta:
        verbose_name = verbose_name_plural = '延时任务'

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.created_time:
            self.created_time = timezone.now()
            
        if not self.doing_time:
            self.doing_time = self.created_time + timezone.timedelta(seconds=self.deadline)
            
        super().save(*args, **kwargs)
